package com.hy.z.config;

import com.hy.z.shiro.ShiroRealm;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    /**
     * @return
     * @Description: 装配自定义Realm
     * @author: FengHongYun
     * @Version: 1.0
     * @CreatedDate: 2020/3/6 0:45
     **/
    @Bean
    public ShiroRealm shiroRealm() {
        return new ShiroRealm();
    }

    /**
     * @return
     * @Description: 配置安全管理器
     * @author: FengHongYun
     * @Version: 1.0
     * @CreatedDate: 2020/3/6 0:45
     **/
    //安全管理器
    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(shiroRealm());
        return securityManager;
    }

    @Bean
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator a = new DefaultAdvisorAutoProxyCreator();
        a.setProxyTargetClass(true);
        return a;
    }

    /**
     * @return
     * @Description: 配置权限过滤器
     * @author: FengHongYun
     * @Version: 1.0
     * @CreatedDate: 2020/3/6 1:01
     **/
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean() {
        ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
        //过滤器要注入安全管理器
        shiroFilter.setSecurityManager(securityManager());
        Map<String, Filter> filters = shiroFilter.getFilters();
        filters.put("authc", new AuthFilter());
        shiroFilter.setFilters(filters);
        //不拦截的路径
        LinkedHashMap<String, String> filterMap = new LinkedHashMap<>();
        filterMap.put("/login", "anon");
        filterMap.put("/checkToken", "anon");
        filterMap.put("/user/uploadImage", "anon");

        //filterMap.put("/","anon");
        //过滤所有请求noSessionCreation,
        filterMap.put("/**", "noSessionCreation,authc");
        shiroFilter.setFilterChainDefinitionMap(filterMap);
        return shiroFilter;
    }

    /**
     * @return
     * @Description: 启用shiro注解
     * @author: FengHongYun
     * @Version: 1.0
     * @CreatedDate: 2020/3/6 1:05
     **/
    @Bean
    public AuthorizationAttributeSourceAdvisor attributeSourceAdvisor() {
        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager());
        return advisor;
    }
}
